class Fruit {
    into(fridge: Fridge) {
        fridge.put(this)
    }
}

class Fridge {
    status: string
    fruits: Fruit[] = []

    open() {
        this.status = "opened"
    }

    put(fruit: Fruit) {
        if (!this.isOpened()) {
            throw new Error("The fridge is not open")
        }
        this.fruits.push(fruit)
    }

    close() {
        this.status = "closed"
    }

    isOpened() {
        return this.status === "opened"
    }
}


interface FridgeRepository {

    findById(fridgeId: string): Fridge

    save(fridge: Fridge): Fridge
}

class FridgeService {

    private readonly fridgeRepository: FridgeRepository

    constructor(fridgeRepository: FridgeRepository) {
        this.fridgeRepository = fridgeRepository
    }

    // /v1/fruits/:fridgeId/open
    public openFridge(fridgeId: string): Fridge {
        const fridge = this.fridgeRepository.findById(fridgeId)
        fridge.open() // Open fridge
        // 省略物联网调用接口...
        return this.fridgeRepository.save(fridge)
    }

    // /v1/fruits/:fridgeId/puts
    public putFruit(fridgeId: string, fruit: Fruit): Fridge {
        const fridge = this.fridgeRepository.findById(fridgeId)
        if (!fridge.isOpened()) {
            throw new Error("The fridge is not open")
        }
        fridge.put(fruit)
        // 省略物联网调用接口...
        return this.fridgeRepository.save(fridge)
    }
}

